package com.spring.sunflower;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;


import android.content.Intent;
import android.graphics.Color;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.enums.PopupAnimation;
import com.spring.sunflower.base.BaseActivity;
import com.spring.sunflower.bean.HelloBean;
import com.spring.sunflower.bean.NewGiftBagBean;
import com.spring.sunflower.bean.SignInBean;
import com.spring.sunflower.bean.VersionBean;
import com.spring.sunflower.constant.Constant;
import com.spring.sunflower.conversation.ConversationManager;
import com.spring.sunflower.dialog.HelloDialog;
import com.spring.sunflower.dialog.NewGiftDialog;
import com.spring.sunflower.dialog.SignInDialog;
import com.spring.sunflower.event.NewMessageComeEvent;
import com.spring.sunflower.main.fragment.DiscoverFragment;
import com.spring.sunflower.main.fragment.MeFragment;
import com.spring.sunflower.main.fragment.MessageFragment;
import com.spring.sunflower.main.adapter.TabLayoutFragmentAdapter;
import com.spring.sunflower.main.fragment.VideoShowFragment;
import com.spring.sunflower.util.LogUtils;
import com.spring.sunflower.widget.NoSmoothViewPager;
import com.tencent.imsdk.v2.V2TIMCallback;
import com.tencent.imsdk.v2.V2TIMManager;
import com.tencent.imsdk.v2.V2TIMValueCallback;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends BaseActivity<MainPresenter> implements MainView, TabLayout.OnTabSelectedListener, ViewPager.OnPageChangeListener {

    private NoSmoothViewPager mViewPager;
    private TabLayout mTabLayout;
    private List<String> mTabList = new ArrayList<>();
    private TabLayoutFragmentAdapter mAdapter;
    private List<Fragment> mFragments = new ArrayList<>();
    private int[] mTabIcons = new int[]{R.drawable.tab_nearby_default,
            R.drawable.tab_square_default,
            R.drawable.tab_message_default,
            R.drawable.tab_my_default};
    private int[] mTabIconsActive = new int[]{R.drawable.tab_nearby_select,
            R.drawable.tab_square_select,
            R.drawable.tab_message_select,
            R.drawable.tab_my_select};
    //灰色以及相对应的RGB值
    private int mGrayColor;
    private int mGrayRed;
    private int mGrayGreen;
    private int mGrayBlue;
    //灰色以及相对应的RGB值
    private int mGreenColor;
    private int mGreenRed;
    private int mGreenGreen;
    private int mGreenBlue;
    private Timer timer;
    private SignInDialog signInDialog;
    private String newer;
    private HelloDialog helloDialog;
    private boolean mHasSayHello, mGetNewGift;//接口都只调用一次
    private String anchorIDList = "";
    private List<HelloBean.DatasBean> mAnchorData = new ArrayList<>();
    private NewGiftDialog newGiftDialog;
    private NewGiftBagBean.DatasBean giftData;

    @Override
    public void doSomethingBeforeOnCreate() {
        super.doSomethingBeforeOnCreate();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    @Override
    public void initView() {
//        WindowInsetsController insetsController = getWindow().getInsetsController();
//        insetsController.setSystemBarsAppearance(WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS,WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS);
        newer = getField(Constant.KEY_NEWER, "");
        String gender = getField(Constant.KEY_GENDER, "");
        mViewPager = findViewById(R.id.viewpager);
        mTabLayout = findViewById(R.id.tab_layout);
        initTabList();
        mAdapter = new TabLayoutFragmentAdapter(getSupportFragmentManager(),
                this, mFragments, mTabList, mTabIcons, mTabIconsActive);
        mViewPager.setAdapter(mAdapter);
        mViewPager.setCurrentItem(0);
        mViewPager.setOffscreenPageLimit(3);
        mTabLayout.setupWithViewPager(mViewPager);
        mTabLayout.setTabMode(TabLayout.MODE_FIXED);
        for (int i = 0; i < mTabLayout.getTabCount(); i++) {
            mTabLayout.getTabAt(i).setCustomView(mAdapter.getTabView(i));
        }
        mTabLayout.addOnTabSelectedListener(this);
        initColor();
        mViewPager.addOnPageChangeListener(this);

        String userID = getField(Constant.KEY_USERID, "");
        String sig = getField(Constant.KEY_SIGNATURE, "");
        MobclickAgent.onProfileSignIn(userID);
        ConversationManager.initV2TIMSDK(this);
        printD("sig=" + sig);
        V2TIMManager.getInstance().login(userID, sig, new V2TIMCallback() {
            //            @Override
            public void onError(int i, String s) {
                printD("IM登录失败=>" + s);
                showToast("IM登录失败code=" + i + ",message=" + s);
            }

            @Override
            public void onSuccess() {
                printD("IM登录成功");
            }
        });
//        TUIKitConfigs configs = TUIKit.getConfigs();
//        configs.setSdkConfig(new V2TIMSDKConfig());
//        configs.setCustomFaceConfig(new CustomFaceConfig());
//        configs.setGeneralConfig(new GeneralConfig());
//        TUIKit.init(this, GenerateTestUserSig.SDKAPPID, configs);
        if (gender.equals(Constant.GENDER_FEMALE)) {
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    mPresenter.keepOnline();
                }
            }, 0, 10000);
        }
        signInDialog = new SignInDialog(this, R.layout.dialog_sign_in);
        signInDialog.setOnSignInListener(new SignInDialog.OnSignInListener() {
            @Override
            public void onSignClick() {
                mPresenter.signIn();
            }

            @Override
            public void onOKClick() {
                signInDialog.dismiss();
            }
        });
        helloDialog = new HelloDialog(this, R.layout.dialog_hello);
        helloDialog.setOnSayHelloListener(new HelloDialog.OnSayHelloListener() {
            @Override
            public void onCreateView() {
                addAnchorList(mAnchorData);
            }

            @Override
            public void onSayHello() {
                mPresenter.sayHello(anchorIDList);
            }
        });
        newGiftDialog = new NewGiftDialog(this, R.layout.dialog_new_gift);
        newGiftDialog.setOnNewGiftListener(new NewGiftDialog.OnNewGiftListener() {
            @Override
            public void onCreateView() {
//                newGiftDialog.setGift(giftData);
            }

            @Override
            public void onGetNewGift() {
                if (!mHasSayHello) {
                    mPresenter.getSayHelloList();
                }
            }
        });
//        mPresenter.getLatestVersion();
        handleSomeAction();
//        TaskFinishDialogUtils.getInstance().show(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        getMsgCount();
    }

    private void getMsgCount() {
        TabLayout.Tab tab = mTabLayout.getTabAt(2);
        View customView = tab.getCustomView();
        TextView tv = customView.findViewById(R.id.tvMessageCount);
        V2TIMManager.getConversationManager().getTotalUnreadMessageCount(new V2TIMValueCallback<Long>() {
            @Override
            public void onSuccess(Long aLong) {
                printD("aLong=" + aLong);
                if (aLong > 0) {
                    tv.setVisibility(View.VISIBLE);
                    tv.setText(String.valueOf(aLong));
                } else {
                    tv.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void onError(int code, String desc) {

            }
        });
    }

    private void handleSomeAction() {
        if ("0".equals(newer)) {
            mPresenter.querySignInRecord();
        }
        if ("1".equals(newer)) {
            mHasSayHello = getField(Constant.KEY_SAY_HELLO, false);
            mGetNewGift = getField(Constant.KEY_NEWER_GIFT, false);
            if (!mGetNewGift) {
                mPresenter.getNewGift();
            }
        }
//        test1();
//        new XPopup.Builder(this)
//                .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
//                .isRequestFocus(false)
//                .dismissOnTouchOutside(false)
//                .autoDismiss(false)
//                .asCustom(newGiftDialog)
//                .show();
    }

    private void initTabList() {
        mTabList.clear();
        mTabList.add(getString(R.string.title_discover));
        mTabList.add(getString(R.string.title_video_show));
        mTabList.add(getString(R.string.title_message));
        mTabList.add(getString(R.string.title_me));
        mFragments.clear();
        mFragments.add(new DiscoverFragment());
        mFragments.add(new VideoShowFragment());
        mFragments.add(new MessageFragment());
        mFragments.add(new MeFragment());
    }

    @Override
    public int getLayoutID() {
        return R.layout.activity_main;
    }

    @Override
    public MainPresenter setPresenter() {
        return new MainPresenter(this);
    }


    private void initColor() {
        mGrayColor = ContextCompat.getColor(this, R.color.gray_1);
        mGrayRed = Color.red(mGrayColor);
        mGrayGreen = Color.green(mGrayColor);
        mGrayBlue = Color.blue(mGrayColor);
        mGreenColor = ContextCompat.getColor(this, R.color.purple_200);
        mGreenRed = Color.red(mGreenColor);
        mGreenGreen = Color.green(mGreenColor);
        mGreenBlue = Color.blue(mGreenColor);
    }

    private int get2Gray(float offset) {
        int red = (int) (1.25 * offset * (mGrayRed - mGreenRed) - 0.125 * mGrayRed + 1.125 * mGreenRed);
        int green = (int) (1.25 * offset * (mGrayGreen - mGreenGreen) - 0.125 * mGrayGreen + 1.125 * mGreenGreen);
        int blue = (int) (1.25 * offset * (mGrayBlue - mGreenBlue) - 0.125 * mGrayBlue + 1.125 * mGreenBlue);
        return Color.argb(255, red, green, blue);
    }

    private int get2Green(float offset) {
        int red = (int) (1.25 * offset * (mGreenRed - mGrayRed) - 0.125 * mGreenRed + 1.125 * mGrayRed);
        int green = (int) (1.25 * offset * (mGreenGreen - mGrayGreen) - 0.125 * mGreenGreen + 1.125 * mGrayGreen);
        int blue = (int) (1.25 * offset * (mGreenBlue - mGrayBlue) - 0.125 * mGreenBlue + 1.125 * mGrayBlue);
        return Color.argb(255, red, green, blue);
    }

    private int getGrayToGreen(float positionOffset) {
        int red = (int) (positionOffset * (mGreenRed - mGrayRed) * 2 + mGrayRed);
        int green = (int) (positionOffset * (mGreenGreen - mGrayGreen) * 2 + mGrayGreen);
        int blue = (int) ((positionOffset) * (mGreenBlue - mGrayBlue) * 2 + mGrayBlue);
//        Log.d("why ", "#### " + red + "  " + green + "  " + blue);
        return Color.argb(255, red, green, blue);
    }

    private int getGreenToGray(float positionOffset) {
        int red = (int) (positionOffset * (mGrayRed - mGreenRed) * 2 + 2 * mGreenRed - mGrayRed);
        int green = (int) (positionOffset * (mGrayGreen - mGreenGreen) * 2 + 2 * mGreenGreen - mGrayGreen);
        int blue = (int) (positionOffset * (mGrayBlue - mGreenBlue) * 2 + 2 * mGreenBlue - mGrayBlue);
//        Log.d("why ", "#### " + red + "  " + green + "  " + blue);
        return Color.argb(255, red, green, blue);
    }

    private long lastTime = 0;

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        int switch2Index = intent.getIntExtra("switch2Index", 0);
        for (int i = 0; i < mTabLayout.getTabCount(); i++) {
            if (switch2Index == i) {
                TabLayout.Tab tab = mTabLayout.getTabAt(switch2Index);
                setTabSelectedState(tab);
                mViewPager.setCurrentItem(switch2Index);
            } else {
                TabLayout.Tab tab = mTabLayout.getTabAt(i);
                setTabUnSelectedState(tab);
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - lastTime) > 2000) {
                showToast(getString(R.string.exit_app_tip));
                lastTime = System.currentTimeMillis();
            } else {
                MobclickAgent.onProfileSignOff();
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer.purge();
            timer = null;
        }
    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        setTabSelectedState(tab);
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {
        setTabUnSelectedState(tab);
    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }


    private void setTabSelectedState(TabLayout.Tab tab) {
        View customView = tab.getCustomView();
        TextView tabText = (TextView) customView.findViewById(R.id.tv_tab_text);
        ImageView tabIcon = (ImageView) customView.findViewById(R.id.iv_tab_icon);
        ImageView tabIconFill = (ImageView) customView.findViewById(R.id.iv_tab_icon_fill);
        tabText.setTextColor(ContextCompat.getColor(this, R.color.colorPrimary));
        String s = tabText.getText().toString();
//        tabIcon.setColorFilter(mGreenColor, PorterDuff.Mode.SRC_IN);
        tabIconFill.setAlpha(1f);
        tabIcon.setAlpha(0f);

    }

    private void setTabUnSelectedState(TabLayout.Tab tab) {
        View customView = tab.getCustomView();
        TextView tabText = (TextView) customView.findViewById(R.id.tv_tab_text);
        ImageView tabIcon = (ImageView) customView.findViewById(R.id.iv_tab_icon);
        ImageView tabIconFill = (ImageView) customView.findViewById(R.id.iv_tab_icon_fill);
        tabText.setTextColor(ContextCompat.getColor(this, R.color.black_alpha_20));
        String s = tabText.getText().toString();
//        tabIcon.setColorFilter(mGrayColor, PorterDuff.Mode.SRC_IN);
        tabIcon.setAlpha(1f);
        tabIconFill.setAlpha(0f);

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//        if (positionOffset > 0) {
//            TabLayout.Tab tabAt = mTabLayout.getTabAt(position);
//            TabLayout.Tab tabAt1 = mTabLayout.getTabAt(position + 1);
//
//            View customView1 = tabAt1.getCustomView();
//            TextView tabText1 = (TextView) customView1.findViewById(R.id.tv_tab_text);
//            ImageView tabIcon1 = (ImageView) customView1.findViewById(R.id.iv_tab_icon);
//            ImageView tabIconFill1 = (ImageView) customView1.findViewById(R.id.iv_tab_icon_fill);
//
//            View customView = tabAt.getCustomView();
//            TextView tabText = (TextView) customView.findViewById(R.id.tv_tab_text);
//            ImageView tabIcon = (ImageView) customView.findViewById(R.id.iv_tab_icon);
//            ImageView tabIconFill = (ImageView) customView.findViewById(R.id.iv_tab_icon_fill);
//            if (positionOffset >= 0.1 && positionOffset <= 0.9) {
//                tabText.setTextColor(get2Gray(positionOffset));
//                tabText1.setTextColor(get2Green(positionOffset));
//            }
//            if (positionOffset < 0.5) {
//                tabIcon.setColorFilter(mGreenColor, PorterDuff.Mode.SRC_IN);
//                tabIcon1.setColorFilter(getGrayToGreen(positionOffset), PorterDuff.Mode.SRC_IN);
//                tabIconFill.setAlpha(1 - 2 * positionOffset);
//                tabIconFill1.setAlpha(0f);
//
//            } else {
//                tabIcon.setColorFilter(getGreenToGray(positionOffset), PorterDuff.Mode.SRC_IN);
//                tabIcon1.setColorFilter(mGreenColor, PorterDuff.Mode.SRC_IN);
//                tabIconFill.setAlpha(0f);
//                tabIconFill1.setAlpha(2 * positionOffset - 1);
//            }
//        }
    }

    @Override
    public void onPageSelected(int position) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void signSuccess(SignInBean.DatasBean data) {
        signInDialog.setHasSigned(true);
        signInDialog.showSignSuccess(data.getAward(), getField(Constant.KEY_GENDER, "1"));
    }

    @Override
    public void signFailed(String data) {
        showToast(data);
        signInDialog.dismiss();
    }

    @Override
    public void noSign() {
        new XPopup.Builder(this)
                .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                .isRequestFocus(false)
                .dismissOnTouchOutside(false)
                .autoDismiss(false)
                .asCustom(signInDialog)
                .show();
    }

    @Override
    public void hasSigned() {

    }

    @Override
    public void sayHello(@Nullable List<HelloBean.DatasBean> data) {
        mAnchorData.clear();
        mAnchorData.addAll(data);
        new XPopup.Builder(this)
                .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                .isRequestFocus(false)
                .dismissOnTouchOutside(false)
                .autoDismiss(false)
                .asCustom(helloDialog)
                .show();
    }

    public void addAnchorList(@Nullable List<HelloBean.DatasBean> data) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < data.size(); i++) {
            helloDialog.addHelloObject(data.get(i));
            stringBuilder.append(data.get(i).getMemberId());
            if (i != data.size() - 1) {
                stringBuilder.append(",");
            }
        }
        anchorIDList = stringBuilder.toString();
    }

    @Override
    public void noSayHello() {

    }

    private void test() {
        String x = "{\n" +
                "\t\"status\": 1,\n" +
                "\t\"message\": \"请求成功\",\n" +
                "\t\"datas\": [{\n" +
                "\t\t\"memberId\": 104032,\n" +
                "\t\t\"nickname\": \"倔强的岳灵珊❁\",\n" +
                "\t\t\"photo\": \"https://yuyue-pro.oss-cn-shenzhen.aliyuncs.com/app/104032/1628413670104.png\",\n" +
                "\t\t\"age\": 25,\n" +
                "\t\t\"city\": \"梧州市\"\n" +
                "\t}, {\n" +
                "\t\t\"memberId\": 104079,\n" +
                "\t\t\"nickname\": \"开心见诚的雅雅♧\",\n" +
                "\t\t\"photo\": \"https://yuyue-pro.oss-cn-shenzhen.aliyuncs.com/app/104079/1628510787497.png\",\n" +
                "\t\t\"age\": 23,\n" +
                "\t\t\"city\": \"梧州市\"\n" +
                "\t}, {\n" +
                "\t\t\"memberId\": 104039,\n" +
                "\t\t\"nickname\": \"小不点❁\",\n" +
                "\t\t\"photo\": \"https://yuyue-pro.oss-cn-shenzhen.aliyuncs.com/app/104039/1628419557326.png\",\n" +
                "\t\t\"age\": 27,\n" +
                "\t\t\"city\": \"梧州市\"\n" +
                "\t}, {\n" +
                "\t\t\"memberId\": 104041,\n" +
                "\t\t\"nickname\": \"勤劳的乖乖✒\",\n" +
                "\t\t\"photo\": \"https://yuyue-pro.oss-cn-shenzhen.aliyuncs.com/app/104041/1628420371784.png\",\n" +
                "\t\t\"age\": 28,\n" +
                "\t\t\"city\": \"梧州市\"\n" +
                "\t}, {\n" +
                "\t\t\"memberId\": 104078,\n" +
                "\t\t\"nickname\": \"娜可露露\",\n" +
                "\t\t\"photo\": \"https://yuyue-pro.oss-cn-shenzhen.aliyuncs.com/app/104078/1628510370625.png\",\n" +
                "\t\t\"age\": 21,\n" +
                "\t\t\"city\": \"梧州市\"\n" +
                "\t}, {\n" +
                "\t\t\"memberId\": 104077,\n" +
                "\t\t\"nickname\": \"诚心诚意的雅雅◇\",\n" +
                "\t\t\"photo\": \"https://yuyue-pro.oss-cn-shenzhen.aliyuncs.com/app/104077/1628509306404.png\",\n" +
                "\t\t\"age\": 22,\n" +
                "\t\t\"city\": \"梧州市\"\n" +
                "\t}]\n" +
                "}";
        Gson gson = new Gson();
        HelloBean helloBean = gson.fromJson(x, HelloBean.class);
        List<HelloBean.DatasBean> datas = helloBean.getDatas();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < datas.size(); i++) {
            helloDialog.addHelloObject(datas.get(i));
            stringBuilder.append(datas.get(i).getMemberId());
            if (i != datas.size() - 1) {
                stringBuilder.append(",");
            }
        }
        anchorIDList = stringBuilder.toString();
    }

    private void test1() {
        String x = "{\n" +
                "    \"status\": 1,\n" +
                "    \"message\": \"请求成功\",\n" +
                "    \"datas\": {\n" +
                "        \"id\": 3,\n" +
                "        \"memberId\": 103197,\n" +
                "        \"createTime\": \"2021-09-01 15:09:09\",\n" +
                "        \"coupon\": 1,\n" +
                "        \"goldCoin\": 100\n" +
                "    }\n" +
                "}";
        Gson gson = new Gson();
        NewGiftBagBean newGiftBagBean = gson.fromJson(x, NewGiftBagBean.class);
        giftData = newGiftBagBean.getDatas();
    }

    @Override
    public void sayHelloSuccess() {
        helloDialog.dismiss();
        showToast("打招呼成功");
        LogUtils.INSTANCE.logD("MessageFragment", "打招呼成功了");
    }

    @Override
    public void sayHelloFailed() {
        helloDialog.dismiss();
    }

    @Override
    public boolean shouldRegisterEventBus() {
        return true;
    }

    @Subscribe
    public void newMessage(NewMessageComeEvent event) {
        getMsgCount();
    }

    @Override
    public void showNewGift(@NonNull NewGiftBagBean.DatasBean data) {
        if (data != null) {
            String coupon = data.getCoupon();
            String goldCoin = data.getGoldCoin();
            if (Integer.valueOf(coupon) > 0 || Integer.valueOf(goldCoin) > 0) {
                giftData = data;
                new XPopup.Builder(this)
                        .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                        .isRequestFocus(false)
                        .dismissOnTouchOutside(false)
                        .autoDismiss(false)
                        .asCustom(newGiftDialog)
                        .show();
            }
        }
    }

    @Override
    public void showNewGiftFailed() {
        if (!mHasSayHello) {
            mPresenter.getSayHelloList();
        }
    }

    @Override
    public void getVersionSuccess(@Nullable VersionBean.DatasBean data) {
        handleSomeAction();
    }

    @Override
    public void getVersionWithNull() {
        handleSomeAction();
    }
}